//
//  IMService.m
//  IMChezhil
//
//  Created by zhangliucheng on 15/7/23.
//  Copyright (c) 2015年 CheZhil. All rights reserved.
//

#import "IMService.h"
#import "IMProcessMessage.h"
#import "IMCore.h"
#import <GCDAsyncSocket.h>

#define HOST_IP @"192.168.1.140"
#define HOST_PORT 5858

#define TAG_HEAD        1
#define TAG_CONTENT     2

KMConnectState connectState;

@interface IMService ()<GCDAsyncSocketDelegate>

@property (strong, nonatomic) GCDAsyncSocket *socket;

@property (strong, nonatomic) NSThread *sendThread;

@property (assign, nonatomic) BOOL isRunning;

@end

@implementation IMService

- (instancetype)init {
    self = [super init];
    if (self) {
        self.isRunning = YES;
    }
    return self;
}

- (void)connectServer {
    @synchronized(self) {
        if (!self.isRunning || connectState == connect_ing || connectState == connect_success) {
            return;
        }
        connectState = connect_ing;
        NSLog(@"开始连接服务器");
        self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
        [self.socket connectToHost:HOST_IP onPort:HOST_PORT error:Nil];
    }
}

- (void)disConnectServer {
    self.isRunning = NO;
    [self.socket disconnect];
}

// 发送消息
- (void)sendMessage {
    while (self.isRunning && [self.socket isConnected]) {
        [IMProcessMessage processSendMessage:self.socket];
    }
}

#pragma mark - GCDAsyncSocketDelegate   
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    NSLog(@"%d  --->  %s", [NSThread isMainThread], __FUNCTION__);
    
    connectState = connect_success;
    // 开始读取信息
    [sock readDataToLength:4 withTimeout:-1 tag:TAG_HEAD];
    
    // 发送验证信息
    [[IMCore shareInstance] sendInitMessage];
    
    self.sendThread = [[NSThread alloc] initWithTarget:self selector:@selector(sendMessage) object:nil];
    [self.sendThread start];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
    NSLog(@"%d  --->  %s    ====== %d", [NSThread isMainThread], __FUNCTION__, sock.isConnected);
    connectState = connect_fail;
    
    // 睡眠两秒后在重新连接
    sleep(2);
    [self connectServer];
}


NSInteger code = 0;
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    if (tag == TAG_HEAD) {
        NSInteger len = 0;
        [data getBytes:&len range:NSMakeRange(0, 2)];
        [data getBytes:&code range:NSMakeRange(2, 2)];
        [sock readDataToLength:len withTimeout:-1 tag:TAG_CONTENT];
        
    } else if (tag == TAG_CONTENT) {
        [sock readDataToLength:4 withTimeout:-1 tag:TAG_HEAD];
        
        NSString* content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [IMProcessMessage processReceiveMessage:code content:content];
    }
}
@end
